/*
 * @lc app=leetcode.cn id=92 lang=cpp
 *
 * [92] 反转链表 II
 */


struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};
// @lc code=start

class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int left, int right) {
        ListNode node; node.next = head; node.val = 501;
        ListNode *pre = &node, *current = &node, *next = head, *l = nullptr, *r = nullptr, *h = nullptr, *tail = nullptr;
        bool flag = false;
        int i = 0;
        while (current) {
            if (i == left) {
                l = pre; flag = true; h = current;
            }
            if (i == right) {
                r = next; tail = current; break; 
            }
            if (!next) break;
            if (flag) {
                ListNode *temp = next; next = next->next;
                temp->next = current; current->next = pre;
                pre = current; current = temp;
            } else {
                pre = current; current = next; next = next->next;
            }
            i++;
        }
        if (l) l->next = tail; 
        if (h) h->next = r;
        return node.next;
    }
};
// @lc code=end

